package com.atguigu.jinx.listener;

import com.atguigu.jinx.service.IRechargeRequestService;
import com.atguigu.jinx.service.impl.MailService;
import com.rabbitmq.client.Channel;
import jakarta.mail.MessagingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import static com.atguigu.jinx.conf.RabbitMQConfig.DEAD_QUEUE_NAME;

/**
 * 队列监听类
 *
 * @author steve
 * @date 2025/08/29 11:56
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DeadLetterListener {

    private final IRechargeRequestService rechargeRequestService;

    private final MailService mailService;

    @Value("${send-email-address}")
    private String sendEmailAddress;

    /**
     * 支付超期订单监听器
     * <p>
     * ACK:消费成功确认
     * NACK:可选择是否重新入队或丢弃(batch or single)
     * REJECT:可选择是否重新入队或丢弃 (single)
     *
     * @param orderNo 订单号
     */
    @RabbitListener(queues = DEAD_QUEUE_NAME, ackMode = "MANUAL")
    public void receiveDead(String orderNo, Channel channel, Message message) throws MessagingException {
        try {
            if (StringUtils.isNotBlank(orderNo)) {
                rechargeRequestService.changeRechargeOrderSyncStatusFromAlipay(orderNo);
            }
            // 业务正常 -> ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("处理订单异常 orderNo={}, err={}", orderNo, e.getMessage(), e);
            // 出异常也 ack 掉，不让消息重回队列
            try {
                // 出异常也 ack 掉，不让消息重回队列
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (Exception ex) {
                log.error("手动 ack 异常", ex);
            } finally {
                mailService.sendSimpleMail(sendEmailAddress,
                        "用户支付超时异常提醒", "下列用户支付超时异常,用户的充值订单号为:".concat(orderNo) + "。请手动进行核销处理");
            }
        }
    }
}
